package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os/exec"
	"regexp"
	"strconv"
	"time"
)

var olsWhen = ""

type SMS struct {
	When        string `json:"when"`
	Content     string `json:"content"`
	Title       string `json:"title"`
	PackageName string `json:"packageName"`
	ID          int    `json:"id"`
}

func getSMS() (smsList []SMS) {
	smsList = []SMS{}

	// 设置超时时间为5秒
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	// 要执行的命令
	cmd := exec.CommandContext(ctx, "termux-notification-list")
	// 执行命令
	if output, err := cmd.Output(); err != nil {
		if ctx.Err() == context.DeadlineExceeded {
			fmt.Println("命令执行超时，已被停止")
			return getSMS()
		} else {
			fmt.Printf("\r命令执行出错: %v", err)
			return
		}
	} else {
		//fmt.Println("命令执行成功")
		//fmt.Println(string(output))
		// 解析JSON数据到SMS结构体切片
		var smss = []SMS{}
		maxWhen := ""
		json.Unmarshal(output, &smss)
		for _, v := range smss {
			if v.When >= olsWhen {
				smsList = append(smsList, v)
				if v.When > maxWhen {
					maxWhen = v.When
				}
			}
		}
		if maxWhen != "" {
			olsWhen = maxWhen
		}
	}
	return
}
func init() {
	ReadToml()
}
func main() {
	oldList := getSMS()
	for {
		time.Sleep(time.Second * 1)
		newList := getSMS()
		//fmt.Println(newList)
		for _, new := range newList {
			have := false
			for _, old := range oldList {
				if new == old {
					have = true
				}
			}
			if have {
				continue
			}
			msg := ""
			if new.Title != "" {
				msg += new.Title
			}
			if new.Content != "" {
				if msg != "" {
					msg += " "
				}
				msg += new.Content
			}
			if msg == "" {
				continue
			}
			fmt.Printf("\r[%v] %v\n", new.When, msg)
			if new.PackageName == "com.tencent.mm" && new.Title == "微信支付" {
				re := regexp.MustCompile(`个人收款码到账¥(\d+(\.\d+)?)`)
				matches := re.FindStringSubmatch(new.Content)
				if matches != nil {
					pricef, _ := strconv.ParseFloat(matches[1], 64)
					price := int64(100 * pricef)
					go payPrice(price, 1)
					//fmt.Printf("\r【微信收款: %v元】\n", matches[1])
					msg = fmt.Sprintf("【微信收款: %v元】\n%v", matches[1], msg)
					//Push(new.When + " 微信收款: " + matches[1])
				}
			} else if new.PackageName == "com.eg.android.AlipayGphone" {
				re := regexp.MustCompile(`你已成功收款(\d+(\.\d+)?)元`)
				matches := re.FindStringSubmatch(new.Title)
				if matches != nil {
					pricef, _ := strconv.ParseFloat(matches[1], 64)
					price := int64(100 * pricef)
					go payPrice(price, 2)
					//fmt.Printf("\r【支付宝收款: %v元】\n", matches[1])
					msg = fmt.Sprintf("【支付宝收款: %v元】\n%v", matches[1], msg)
					//Push(new.When + " 支付宝收款: " + matches[1])
				}
			}
			go Push(fmt.Sprintf("%v\n%v", msg, new.When))
		}
		oldList = newList
	}

}

func Push(msg string) {
	//这里可以自行设置推送通知
}
func Post(price, payMethod int64) {
	// 定义 JSON 数据的结构
	type Payload struct {
		Key    string `json:"key"`
		Price  int64  `json:"price"`
		Method int64  `json:"method"`
	}
	// 创建 JSON 数据
	payload := Payload{
		Key:    tomlInfo.Key,
		Price:  price,
		Method: payMethod,
	}
	// 将数据序列化为 JSON
	jsonData, _ := json.Marshal(payload)
	// 创建请求
	req, err := http.NewRequest("POST", tomlInfo.Post, bytes.NewBuffer(jsonData))
	if err != nil {
		printtf("Error occurred during creating request. Error: %s\n", err.Error())
		return
	}
	// 设置请求头
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	printtf("Response Body: %s", string(body))
}
